//
//  RegisterViewController.swift
//  ZCF
//
//  Created by 赵世杰 on 16/4/29.
//  Copyright © 2016年 zhaoshijie. All rights reserved.
//

import UIKit

class RegisterViewController: BaseViewController {
    
    ///  数据
    
    // 图形字典数据
    var randomDic:[AnyHashable: Any]!
    // 验证码的时间
    var identifyingCodeTime:Int!
    // 当前过去的时间
    var newTime:Int!
    
    
    // 定时器
    var timer:Timer!
    
    // 控件
    @IBOutlet var agreementWebView: UIWebView!
    @IBOutlet var closeAgreementButton: UIButton!
    
    @IBOutlet var graphicaltextField: UITextField!
    @IBOutlet var telephoneTextField: UITextField!
    @IBOutlet var identifyingCodeTextField: UITextField!
    @IBOutlet var passwordTextField: UITextField!
    
    @IBOutlet var identifyingCodeButton: UIButton!
    @IBOutlet var getIdentifyingCodeButton: UIButton!
    
    
    
    
    //MARK: - 方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        
        // 加载图形验证码
        self.randomDic = CommonTool.getImageCode(withUrl: HttpUrl) as Dictionary
        self.identifyingCodeButton.setBackgroundImage(self.randomDic["image"] as? UIImage, for: UIControlState())
        
        
        // 初始化数据
        self._initData()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        if (self.timer != nil)
        {
            self.timer.invalidate()
        }
        
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化数据
        self._initData()
        // 网络请求
        self._requestData()
    }
    
    
    func _initData()
    {
        self.newTime = 0
        self.identifyingCodeTime = 300
    }
    
    //MARK: - 网络请求
    func _requestData()
    {
        
    }
    
    // 请求手机验证码
    func requestTelephoneCode()
    {
        let requestUrl = HttpUrl + "/regist/send/sms/code"
        let requestHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let paramDic:[String:String] = ["ran":self.randomDic["number"]! as! String,"mobile":self.telephoneTextField.text!,"imageCode":self.graphicaltextField.text!]
        let request = HTTPRequest()
        request.POSTRequest(requestUrl, httpHeader: requestHeader, parameters: paramDic, resultBlock: { (result) -> Void in
//            print("请求成功")
            print(result)
            if RequestTool.sjGetString(result["code"]) == "200"
            {
                let promp = SJPromptView()
                promp.textString = "获取验证码成功"
                promp.addTo(withController: self, withFrame: CGRect(x: 120, y: KScreenHeight-100, width: KScreenWidth-240, height: 30), withTime: 1)
                // 取数据
                let data:[String:AnyObject] = result["data"] as! Dictionary
                self.identifyingCodeTime = (data["limitSeconds"] as! NSNumber).intValue
                self.getIdentifyingCodeButton.setTitle(String(self.identifyingCodeTime) + " S", for: UIControlState())
                print(self.identifyingCodeTime)
                
                // 开启定时器
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(RegisterViewController.timerAction), userInfo: nil, repeats: true)
                // 关闭button的点击事件
                self.getIdentifyingCodeButton.setImage(nil, for: UIControlState())
                self.getIdentifyingCodeButton.isUserInteractionEnabled = false
            }
            else
            {
                let promp = SJPromptView()
                promp.textString = RequestTool.messgeDeal(withCode: RequestTool.sjGetString(result["code"]), message: RequestTool.sjGetString(result["message"]))
                promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenHeight-100, width: KScreenWidth-200, height: 30), withTime: 1)
                // 开启定时器
                self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(RegisterViewController.timerAction), userInfo: nil, repeats: true)
                // 关闭button的点击事件
                self.getIdentifyingCodeButton.setImage(nil, for: UIControlState())
                self.getIdentifyingCodeButton.isUserInteractionEnabled = false
            }
            
            }) { () -> Void in
                print("请求失败")
        }
        
    }
    
    // 注册请求
    func requestRegister(_ passwordMD5:String)
    {
        let urlString:String = HttpUrl + "/mobile/regist"
        let requestHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let paramDic:[String:String] = ["ran":self.randomDic["number"] as! String , "imageCode":self.graphicaltextField.text! , "mobile":self.telephoneTextField.text! , "smsCode":self.identifyingCodeTextField.text! , "password":passwordMD5]
        let request = HTTPRequest()
        request.POSTRequest(urlString, httpHeader: requestHeader, parameters:paramDic, resultBlock: { (result) -> Void in
            print("请求成功")
            print(result)
            // 取数据
            let data:[String:AnyObject] = result["data"] as! Dictionary
            if RequestTool.sjGetString(data["code"]) == "200"
            {
                // 请求成功,存储数据
                let data2:[String:AnyObject] = data["data"] as! Dictionary
                let userSingle = UserSingle.instance ;
                userSingle.token = data2["token"] as! String
                userSingle.userId = data2["userId"] as! String
                // 跳转
                self .dismiss(animated: true, completion: nil)
            }
            else
            {
                let promp = SJPromptView()
                promp.textString = RequestTool.messgeDeal(withCode: RequestTool.sjGetString(data["code"]), message: RequestTool.sjGetString(data["message"]))
                promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenHeight-100, width: KScreenWidth-200, height: 30), withTime: 1)
            }
            }) { () -> Void in
                print("请求失败")
        }
    }
    
    

    
    
    //MARK: - 响应事件
    
    // 定时器响应方法
    func timerAction()
    {
        let intervalTime = self.identifyingCodeTime - self.newTime
        self.getIdentifyingCodeButton.setTitle(String(intervalTime) + " S", for: UIControlState())
        // 当计时器的时间走完的时候
        if intervalTime <= 0
        {
            self.timer.invalidate()
            self.newTime = 0
            self.getIdentifyingCodeButton.setImage(UIImage(named: "zhuce_16"), for:UIControlState())
            self.getIdentifyingCodeButton.isUserInteractionEnabled = true
        }
        self.newTime = self.newTime + 1
    }
    
    // 显示协议
    @IBAction func showAgreementAction(_ sender: AnyObject) {
        UIView .animate(withDuration: 0.5, animations: { () -> Void in
            self.agreementWebView.isHidden = false
            self.closeAgreementButton.isHidden = false
        }) 
        
    }
    // 关闭协议
    @IBAction func closeAgreementAciton(_ sender: AnyObject) {
        UIView.animate(withDuration: 0.5, animations: { () -> Void in
            self.agreementWebView.isHidden = true
            self.closeAgreementButton.isHidden = true
        }) 
    }
    // 切换图形验证码
    @IBAction func changeIdentifyingCodeAction(_ sender: AnyObject) {
        // 加载图形验证码
        self.randomDic = CommonTool.getImageCode(withUrl: HttpUrl) as Dictionary
        self.identifyingCodeButton.setBackgroundImage(self.randomDic["image"] as? UIImage, for: UIControlState())

    }
    // 获取手机验证码
    @IBAction func getIdentifyingCodeAction(_ sender: AnyObject) {
        
        // 取消textField的第一响应事件
        self.graphicaltextField.resignFirstResponder()
        self.telephoneTextField.resignFirstResponder()
        self.identifyingCodeTextField.resignFirstResponder()
        self.passwordTextField.resignFirstResponder()
        
        // 判断正确的图形验证码
        if self.graphicaltextField.text!.isEmpty
        {
            let promp = SJPromptView()
            promp.textString = "验证码不能为空"
            promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenHeight-100, width: KScreenWidth-200, height: 30), withTime: 1)
            return
        }
        
        // 判断正确的
        if self.telephoneTextField.text!.isEmpty
        {
            let promp = SJPromptView()
            promp.textString = "手机号码不能为空"
            promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenHeight-100, width: KScreenWidth-200, height: 30), withTime: 1)
            return
        }
        else if !RegularExpression.isMobileNumber(self.telephoneTextField.text)
        {
            let promp = SJPromptView()
            promp.textString = "手机号码的格式不正确"
            promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenHeight-100, width: KScreenWidth-200, height: 30), withTime: 1)
            return
        }
        
        // 请求手机验证码
        self.requestTelephoneCode()

        
    }
    // 注册
    @IBAction func registerAction(_ sender: AnyObject) {
        
        // 图形验证码
        if self.graphicaltextField.text!.isEmpty
        {
            let promp = SJPromptView()
            promp.textString = "验证码为空"
            promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenWidth-100, width: KScreenWidth-200, height: 30), withTime: 1)
            return
        }
        
        // 手机号码
        else if !RegularExpression.isMobileNumber(self.telephoneTextField.text)
        {
            let promp = SJPromptView()
            promp.textString = "手机号码的格式不对"
            promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenWidth-100, width: KScreenWidth-200, height: 30), withTime: 1)
            return
        }
        
        // 短信验证码
        else if self.identifyingCodeTextField.text!.isEmpty
        {
            let promp = SJPromptView()
            promp.textString = "短信验证码不能为空"
            promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenWidth-100, width: KScreenWidth-200, height: 30), withTime: 1)
            return
        }
        
        // 密码设置
        else if !RegularExpression.isPasswordTure(self.passwordTextField.text)
        {
            let promp = SJPromptView()
            promp.textString = "密码格式不对"
            promp.addTo(withController: self, withFrame: CGRect(x: 100, y: KScreenWidth-100, width: KScreenWidth-200, height: 30), withTime: 1)
            return
        }
        
        // 大写MD5处理
        let passwordMD5 = CommonTool.md5(self.passwordTextField.text).uppercased() 
        // 请求
        self.requestRegister(passwordMD5)
    }
    
    
    
}
